<template>
  <Card class="!m-10px">
    <Form :label-col="{ span: 3 }">
      <FormItem label="SPU名称">{{ props.spu.spuName }}</FormItem>
      <FormItem label="SKU名称" v-bind="validateInfos.skuName">
        <Input placeholder="请输入SKU名称" v-model:value="sku.skuName" />
      </FormItem>
      <FormItem label="SKU价格" v-bind="validateInfos.price">
        <InputNumber
          placeholder="请输入SKU价格"
          :min="0"
          class="!w-300px"
          v-model:value="sku.price"
        />
      </FormItem>
      <FormItem label="SKU重量" v-bind="validateInfos.weight">
        <InputNumber
          placeholder="请输入SKU重量"
          :min="0"
          class="!w-300px"
          v-model:value="sku.weight"
        />
      </FormItem>
      <FormItem label="SKU描述" v-bind="validateInfos.skuDesc">
        <Textarea placeholder="请输入SKU描述" v-model:value="sku.skuDesc" />
      </FormItem>
      <FormItem label="SKU品牌" :wrapper-col="{ span: 6 }" v-bind="validateInfos.tmId">
        <Select placeholder="请选择SKU品牌" v-model:value="sku.tmId">
          <SelectOption v-for="tm in trademarkList" :key="tm.id" :value="tm.id">
            {{ tm.tmName }}
          </SelectOption>
        </Select>
      </FormItem>
      <FormItem label="平台属性" v-bind="validateInfos.skuAttrValueList">
        <Row :gutter="20">
          <Col
            v-for="(attr, index) in attrList"
            :key="attr.id"
            :xs="24"
            :sm="12"
            :lg="8"
            :xl="6"
            :xxl="4"
          >
            <FormItem
              :label="attr.attrName"
              :label-col="{
                span: 6,
              }"
              :wrapper-col="{
                span: 18,
              }"
            >
              <Select placeholder="请选择平台属性" v-model:value="sku.skuAttrValueList[index]">
                <SelectOption
                  v-for="attrValue in attr.attrValueList"
                  :key="attrValue.id"
                  :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`"
                >
                  {{ attrValue.valueName }}
                </SelectOption>
              </Select>
            </FormItem>
          </Col>
        </Row>
      </FormItem>
      <FormItem label="销售属性" v-bind="validateInfos.skuSaleAttrValueList">
        <Row :gutter="20">
          <Col
            v-for="(saleAttr, index) in spuSaleAttrList"
            :key="saleAttr.id"
            :xs="24"
            :sm="12"
            :lg="8"
            :xl="6"
            :xxl="4"
          >
            <!-- <FormItem
              :label="saleAttr.saleAttrName"
              :label-col="{
                span: saleAttr.saleAttrName.length > 2 ? 6 + saleAttr.saleAttrName.length - 1 : 6,
              }"
              :wrapper-col="{
                span:
                  saleAttr.saleAttrName.length > 2 ? 18 - (saleAttr.saleAttrName.length - 1) : 18,
              }"
            > -->
            <FormItem
              :label="saleAttr.saleAttrName"
              :label-col="{
                span: 6,
              }"
              :wrapper-col="{
                span: 18,
              }"
            >
              <Select placeholder="请选择销售属性" v-model:value="sku.skuSaleAttrValueList[index]">
                <SelectOption
                  v-for="saleAttrValue in saleAttr.spuSaleAttrValueList"
                  :key="saleAttrValue.id"
                  :value="`${saleAttr.id}:${saleAttr.saleAttrName}:${saleAttrValue.id}:${saleAttrValue.saleAttrValueName}`"
                >
                  {{ saleAttrValue.saleAttrValueName }}
                </SelectOption>
              </Select>
            </FormItem>
          </Col>
        </Row>
      </FormItem>
      <FormItem label="SKU图片" v-bind="validateInfos.skuImageList">
        <Table
          :columns="columns"
          :data-source="spuImageList"
          :row-selection="rowSelection"
          bordered
          :pagination="false"
          rowKey="id"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'imgUrl'">
              <img class="w-200px h-100px" :src="record.imgUrl" :alt="record.imgName" />
            </template>
            <template v-if="column.dataIndex === 'operator'">
              <Button disabled v-if="record.isDefault === '1'">默认图片</Button>
              <Button type="primary" @click="setDefaultImg(record)" v-else>设置默认图片</Button>
            </template>
          </template>
        </Table>
      </FormItem>
      <FormItem :wrapper-col="{ offset: 3 }">
        <Button type="primary" class="!mr-10px" @click.prevent="submit">确定</Button>
        <Button @click="emits('setIsShow', CompNames.SPU_LIST)">取消</Button>
      </FormItem>
    </Form>
  </Card>
</template>

<script lang="ts">
  import { defineComponent } from 'vue';

  export default defineComponent({
    name: 'AddOrUpdateSku',
  });
</script>

<script lang="ts" setup>
  import { ref, onMounted, reactive } from 'vue';
  import {
    Card,
    Form,
    FormItem,
    Input,
    InputNumber,
    Textarea,
    Select,
    SelectOption,
    Table,
    Button,
    Row,
    Col,
    message,
  } from 'ant-design-vue';
  import { TrademarkListModel } from '/@/api/product/model/trademarkModel';
  import { AttrListModel } from '/@/api/product/model/attrModel';
  import { getAllTrademarkListApi } from '/@/api/product/trademark';
  import { getAttrListApi } from '/@/api/product/attr';
  import { getSpuImageListApi, getSpuSaleAttrListApi } from '/@/api/product/spu';
  import { saveSkuApi } from '/@/api/product/sku';
  import { SkuImageModel, SkuImageListModel } from '/@/api/product/model/skuModel';
  import { SpuImageListModel, SpuSaleAttrListModel } from '/@/api/product/model/spuModel';
  import { useCategoryStore } from '/@/store/modules/category';
  import { CompNames } from '../types';

  const emits = defineEmits(['setIsShow']);
  const props = defineProps<{
    spu: {
      id: number;
      spuName: string;
    };
  }>();

  const categoryStore = useCategoryStore();

  const columns = [
    {
      title: '图片',
      dataIndex: 'imgUrl',
    },
    {
      title: '名称',
      dataIndex: 'imgName',
    },
    {
      title: '操作',
      className: 'w-150px',
      dataIndex: 'operator',
    },
  ];
  // const skuImageList = [{}];

  // const selectedRow = ref<any[]>([]);

  const rowSelection = ref({
    checkStrictly: false,
    onChange: (_, rows) => {
      sku.skuImageList = rows;
    },
    // selectedRowKeys: selectedRow.value,
    // onSelect: (record: DataItem, selected: boolean, selectedRows: DataItem[]) => {
    //   console.log('onSelect', record, selected, selectedRows);
    // },
    // onSelectAll: (selected: boolean, selectedRows: DataItem[], changeRows: DataItem[]) => {
    //   console.log('onSelectAll', selected, selectedRows, changeRows);
    // },
  });

  const trademarkList = ref<TrademarkListModel>([]);
  const attrList = ref<AttrListModel>([]);
  const spuImageList = ref<SpuImageListModel>([]);
  const spuSaleAttrList = ref<SpuSaleAttrListModel>([]);

  const sku = reactive({
    skuName: '',
    price: 0,
    weight: 0,
    skuDesc: '',
    tmId: undefined,
    // 平台属性
    skuAttrValueList: [
      // {
      //   attrId: 0,
      //   attrName: 'string',
      //   valueId: 0,
      //   valueName: 'string',
      // },
    ],
    skuSaleAttrValueList: [
      // {
      //   saleAttrId: 0,
      //   saleAttrName: 'string',
      //   saleAttrValueId: 0,
      //   saleAttrValueName: 'string',
      //   spuId: 0,
      // },
    ],
    // 默认图片
    skuDefaultImg: '',
    skuImageList: [
      // {
      //   imgName: 'string',
      //   imgUrl: 'string',
      //   isDefault: 'string',
      //   spuImgId: 0,
      // },
    ],
    // spuId: 0,
  });

  // _rule 形参不使用不会报错
  const validator = (_rule, value: SkuImageListModel) => {
    if (value.length === 0) {
      return Promise.reject('至少选中一张图片');
    }
    if (value.some((img) => img.isDefault === '1')) {
      return Promise.resolve();
    }
    return Promise.reject('至少设置一张默认图片');
  };

  const rules = reactive({
    skuName: [{ required: true, message: '请输入SKU名称', trigger: 'blur' }],
    price: [{ required: true, message: '请输入SKU价格' }],
    weight: [{ required: true, message: '请输入SKU重量' }],
    skuDesc: [{ required: true, message: '请输入SKU描述', trigger: 'blur' }],
    tmId: [{ required: true, message: '请选择SKU品牌' }],
    skuAttrValueList: [{ required: true, message: '请选择平台属性', type: 'array' }],
    skuSaleAttrValueList: [{ required: true, message: '请选择销售属性', type: 'array' }],
    // 同时可能会出现两个错误
    // skuImageList: [{ required: true, message: '请选择SKU图片', type: 'array' }, { validator }],
    // validator自定义校验规则
    skuImageList: [{ required: true, validator }],
  });

  const { validateInfos, validate } = Form.useForm(sku, rules);

  onMounted(async () => {
    trademarkList.value = await getAllTrademarkListApi();
  });
  onMounted(async () => {
    attrList.value = await getAttrListApi({
      category1Id: categoryStore.getCategory1Id as number,
      category2Id: categoryStore.getCategory2Id as number,
      category3Id: categoryStore.getCategory3Id as number,
    });
  });
  onMounted(async () => {
    spuImageList.value = await getSpuImageListApi(props.spu.id);
  });
  onMounted(async () => {
    spuSaleAttrList.value = await getSpuSaleAttrListApi(props.spu.id);
  });

  const setDefaultImg = (skuImage: SkuImageModel) => {
    spuImageList.value.forEach((skuImage: SkuImageModel) => {
      skuImage.isDefault = '0';
    });
    skuImage.isDefault = '1';
  };

  const submit = async () => {
    await validate();
    await saveSkuApi({
      ...sku,
      spuId: props.spu.id,
      category3Id: categoryStore.category3Id as number,
      skuAttrValueList: sku.skuAttrValueList.filter(Boolean).map((str: string) => {
        const [attrId, attrName, valueId, valueName] = str.split(':');
        return {
          attrId: +attrId,
          valueId: +valueId,
          attrName,
          valueName,
        };
      }),
      skuSaleAttrValueList: sku.skuSaleAttrValueList.filter(Boolean).map((str: string) => {
        const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] = str.split(':');
        return {
          saleAttrId: +saleAttrId,
          saleAttrName,
          saleAttrValueId: +saleAttrValueId,
          saleAttrValueName,
          spuId: props.spu.id,
        };
      }),
      skuDefaultImg: (sku.skuImageList.find((img: SkuImageModel) => img.isDefault === '1') as any)
        .imgUrl,
    });
    message.success('添加SKU成功');
    emits('setIsShow', CompNames.SPU_LIST);
  };
</script>
